package vip.ola.pay.batchpay.xinglandf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.DateUtil;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.PayInterface;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchTrans;
import vip.ola.pay.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_SUCCESS;

@RequestMapping("/api/xinglandf")
@Controller
public class XinglandfTransController extends BaseController {

    private static final MyLog _log = MyLog.getLog(XinglandfTransController.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    @Autowired
    public BaseNotify4MchTrans baseNotify4MchTrans;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestParam Map<String,String> object, HttpServletRequest request){
        _log.info("接收XinglandfTransController回调：" + object);
        // 判断请求IP是否允许+"："
        String clintIp = IPUtility.getClientIp(request);
        PayInterface payInterface = rpcCommonService.rpcPayInterfaceService.findByCode("feifandf");
        String whiteIps=payInterface.getRemark();
        _log.info("请求ip为：" + clintIp+"  维护白名单ip： "+ whiteIps);
        if (StringUtils.isEmpty(whiteIps) || !Arrays.asList(whiteIps.split("\\,")).contains(clintIp)){
            _log.info( "IP[" + clintIp + "]不允许访问");
            return "ip fail";
        }
        String transOrderId = object.get("out_trade_no");
        TransOrder payOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        if(payOrder == null){
            return "order not exist!";
        }

        Long orderMoney = new BigDecimal(object.get("amount")).multiply(BigDecimal.valueOf(100)).longValue();
        if (orderMoney.longValue() != payOrder.getAmount().longValue()){
            return "money fail";
        }

        if (payOrder.getStatus() == TRANS_STATUS_SUCCESS || payOrder.getStatus() == TRANS_STATUS_COMPLETE) {
            return "OK";
        }
        AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
        String retSign = object.get("payment_md5sign");
        String privateKey = accountParams.getString("privateKey");
        object.remove("sign");
        String sign = null;
        try {
            sign = PayDigestUtil.getSign(object, privateKey);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        ;
        _log.info("加签信息：map-{},sign->{}", object, sign );
        if (retSign.equals(sign)){
            if ("success".equals(object.get("status")) && "1".equals(object.get("refCode"))){
                //查询代付结果
                String queryUrl = accountParams.getString("queryUrl");
                String mchId = payPassageAccount.getPassageMchId();
                Map<String,Object> maps = new HashMap<>();
                maps.put("payment_memberid",mchId);
                maps.put("payment_orderid",transOrderId);
                String querySign = PayDigestUtil.getSign(maps, privateKey);  //签名
                maps.put("payment_md5sign", querySign);
                _log.info("FeifandfTransService订单查询请求={}",maps);
                NameValuePair pair = new BasicNameValuePair("payment_memberid", mchId);
                NameValuePair pair3 = new BasicNameValuePair("payment_orderid", transOrderId);
                NameValuePair pair4 = new BasicNameValuePair("payment_md5sign", querySign);
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
                nameValuePairs.add(pair);
                nameValuePairs.add(pair3);
                nameValuePairs.add(pair4);
                String respDetail = XinglandfTransService.postWithParamsForString(queryUrl,nameValuePairs);
                _log.info("XinglandfTransController-》订单查询返回={}",respDetail);
                if (StringUtils.isNotEmpty(respDetail)){
                    JSONObject resObj = JSON.parseObject(respDetail);
                    if ("success".equals(resObj.getString("status")))
                    {
                        String queryStatus = resObj.getString("refCode");
                        if ("1".equals(queryStatus) ){
                            String channelOrderNo = object.get("transaction_id");
                            int result =  rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId, channelOrderNo);
                            _log.info("更新订单状态为支付成功: result={}", result);
                            if(result == 1){
                                // 通知业务系统
                                baseNotify4MchTrans.doNotify(payOrder, true);
                                return "OK";
                            }
                        }else {
                            _log.info("query status is error,the mchOrderNo:"+transOrderId);
                            return "query error";
                        }
                    }else {
                        _log.info("query detail is error,the mchOrderNo:"+transOrderId);
                        return "query detail error";
                    }
                }else {
                    _log.error("订单查询异常，the mchorderno:" +transOrderId);
                    return "query error";
                }
            }else {
                    _log.info("orderStatus error");

            }

        }else {
            _log.info("sign error");
        }
        return "fail!";
    }



}
